package com.example.demo.admin.sync.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.example.demo.admin.sync.utils.HttpUtils;
import com.example.demo.admin.sync.utils.ListUtils;
import com.example.demo.admin.sync.vo.ApiOrgInfoVo;
import com.example.demo.admin.sync.vo.ApiUserInfoVo;
import com.example.demo.common.persistence.dao.MemOrgMapper;
import com.example.demo.common.persistence.dao.MemUserMapper;
import com.example.demo.common.persistence.model.MemOrg;
import com.example.demo.common.persistence.model.MemUser;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.example.demo.admin.sync.cas.PasswordCheck.encryModeBid;


/**
 * @author wyz-pc 2017年5月12日 下午2:31:51
 *
 */
@Service
public class PushDataApi {
	private static Logger logger = LoggerFactory.getLogger(PushDataApi.class);

	private static String PUSH_SUCCESS = "0";

	private final String appId = "zjpt_ebs";// configService.getString("api.appId");

	private final String accessToken_url = "https://devapi.zcjb.com.cn/mem/user/passport/accessToken.htm";// configService.getString("api.accessToken");
	private final String pushNewUser_url = "https://devapi.zcjb.com.cn/mem/user/passport/pushNewUser";// configService.getString("api.pushNewUser");
	private final String getUserInfo_url = "https://devapi.zcjb.com.cn/mem/user/passport/getUserInfo";// configService.getString("api.getUserInfo");
	private final String orgVerify_url = "https://devapi.zcjb.com.cn/mem/user/passport/pushNewOrg.htm";// configService.getString("api.orgVerify");
	private final String updateUserInfo_url = "https://devapi.zcjb.com.cn/mem/user/passport/updateUserInfo";// configService.getString("api.updateUserInfo");
	private final String updateOrgInfo_url = "https://devapi.zcjb.com.cn/mem/user/passport/updateOrgInfo";// configService.getString("api.updateOrgInfo");
	private final String updateOrgUser_url = "https://devapi.zcjb.com.cn/mem/user/passport/updateOrgUser";// configService.getString("api.updateOrgUser");
	private final String checkUserInfo_url = "https://devapi.zcjb.com.cn/mem/user/passport/checkUserInfo";// configService.getString("api.checkUserInfo");
	private final String checkOrgInfo_url = "https://devapi.zcjb.com.cn/mem/user/passport/checkOrgInfo";// configService.getString("api.checkOrgInfo");
	private final String checkUserData_url = "https://devapi.zcjb.com.cn/mem/user/passport/checkUserData";// configService.getString("api.checkUserData");
	private final String pushOldUser_url = "https://devapi.zcjb.com.cn/mem/user/passport/pushOldUser";// configService.getString("api.pushOldUser");
	private final String addOrgUser_url = "https://devapi.zcjb.com.cn/mem/user/passport/addOrgUser.htm";// configService.getString("api.addOrgUser");
	private final String checkOrgData_url = "https://devapi.zcjb.com.cn/mem/user/passport/checkOrgData.htm";// configService.getString("api.checkOrgData");
	private final String pushOldOrg_url = "https://devapi.zcjb.com.cn/mem/user/passport/pushOldOrg.htm";// configService.getString("api.pushOldOrg");
	private final String pushUserNewPassword_url="https://devapi.zcjb.com.cn/mem/user/passport/pushUserNewPassword.htm";
	private final String appSecret = "zjpt_ebs616";// configService.getString("api.pushOldOrg");


	@Autowired
	private MemUserMapper memUserMapper;
	@Autowired
	private MemOrgMapper memOrgMapper;

	private ExecutorService executorService = Executors.newFixedThreadPool(2);


	/**
	 * @author wyz-pc 2017年5月12日 下午2:42:12
	 * @return token/code/msg
	 * @Description 获取token
	 */
	private String accessToken() {


		Map<String, Object> params = new HashMap<String, Object>();
		params.put("appId",appId);
		params.put("appSecret", appSecret);

		String jsonData = JSON.toJSONString(params);

		String result = HttpUtils.sendPostJson(accessToken_url, jsonData);

		return JSON.parseObject(result).getString("token");
	}

	/**
	 * 检查统一认证开关
	 * @return
	 */
	private Boolean checkCas(){
		String flag = "true";

		return StringUtils.equals(flag,"false") ? false : true;

	}

	/**
	 * 修改密码时推向接口
	 * @param userName
	 * @param password
	 * @param salt
	 * @return
	 */
	public String pushUserNewPassword(String userName,String password,String salt){

		if(!checkCas())
			return null;

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("token", this.accessToken());
		params.put("userName", userName);
		params.put("password", password);
		params.put("salt", salt);
		params.put("encryMode",encryModeBid);

		String jsonData = JSON.toJSONString(params);
		logger.info("pushUserNewPassword+params->{}", jsonData);
		String result = HttpUtils.sendPostJson(pushUserNewPassword_url, jsonData);
		logger.info("pushUserNewPassword+result->{}", result);

		//String code = JSON.parseObject(result).getString("code");

		return result;

	}


	/**
	 * @author wyz-pc 2017年5月12日 下午2:46:18
	 * @param apiUserInfoVo
	 * @return code/msg/username
	 * @Description 注册新用户时推向接口
	 */
	public String pushNewUser(ApiUserInfoVo apiUserInfoVo) {

		executorService.submit(()->{
			String token = this.accessToken();

			apiUserInfoVo.setSysCode(this.getAppId());
			apiUserInfoVo.setOldId(apiUserInfoVo.getId());
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("token", token);
			params.put("userInfo", apiUserInfoVo);

			String jsonData =  JSON.toJSONString(params);


			logger.info("getUserInfo+param->{}", jsonData);
			String result = HttpUtils.sendPostJson(pushNewUser_url, jsonData);
			logger.info("getUserInfo+result->{}", result);

			MemUser user = new MemUser();
			user.setId(apiUserInfoVo.getId());
			user.setSuuid(JSON.parseObject(result).getString("suuid"));
			user.updateById();


		});

		return null;
	}

	/**
	 * @author wyz-pc 2017年5月12日 下午2:53:05
	 * @param username
	 * @return msg/code/userInfo
	 * @Description 获取用户信息
	 */
	public String getUserInfo(String username) {

		if(!checkCas())
			return null;

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("token", this.accessToken());
		params.put("username", username);

		String jsonData = JSON.toJSONString(params);
		logger.info("getUserInfo+param->{}", jsonData);
		String result = HttpUtils.sendPostJson(getUserInfo_url, jsonData);
		logger.info("getUserInfo+result->{}", result);

		return result;
		//return JSON.parseObject(result).getString("userInfo");
	}

	/**
	 * @author wyz-pc 2017年5月12日 下午3:07:18
	 * @param username
	 * @param apiOrgInfoVo
	 * @return code/msg
	 * @Description 注册机构
	 */
	public String orgVerify(String username, ApiOrgInfoVo apiOrgInfoVo) {


			apiOrgInfoVo.setAppId(this.getAppId());
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("token", this.accessToken());
			params.put("username", username);
			params.put("orgInfo", apiOrgInfoVo);
			String jsonData = JSON.toJSONString(params);
			logger.info("orgVerify+params->{}", jsonData);
			String result = HttpUtils.sendPostJson(orgVerify_url, jsonData);
			logger.info("orgVerify+result->{}", result);

			String suuid = JSON.parseObject("result").getString("suuid");

			MemOrg bean = new MemOrg();
			bean.setId(apiOrgInfoVo.getId());
			bean.setSuuid(suuid);

			memOrgMapper.updateById(bean);

		   return result;
	}

	/**
	 * @author wyz-pc 2017年5月12日 下午3:10:46
	 * @param apiUserInfoVo
	 * @return code/msg
	 * @Description 修改更新用户信息
	 */
	public String updateUserInfo(ApiUserInfoVo apiUserInfoVo) {


			Map<String, Object> params = new HashMap<String, Object>();
			params.put("token", this.accessToken());
			params.put("userInfo", JSON.toJSONString(apiUserInfoVo));
			String jsonData = JSON.toJSONString(params);
			logger.info("updateUserInfo+params->{}", jsonData);
			String result = HttpUtils.sendPostJson(updateUserInfo_url,jsonData);
			logger.info("updateUserInfo+result->{}", result);

		    return result;
	}

	/**
	 * @author wyz-pc 2017年5月12日 下午3:13:12
	 * @param apiOrgInfoVo
	 * @return
	 * @Description 修改更新企业信息
	 */
	public String updateOrgInfo(String username, ApiOrgInfoVo apiOrgInfoVo) {


			Map<String, Object> params = new HashMap<String, Object>();
			params.put("token", this.accessToken());
			params.put("username", username);
			params.put("orgInfo", JSON.toJSONString(apiOrgInfoVo));
			String jsonData = JSON.toJSONString(params);
			logger.info("updateOrgInfo+params->{}", jsonData);
			String result = HttpUtils.sendPostJson(updateOrgInfo_url,jsonData);
			logger.info("updateOrgInfo+result->{}", result);

		    return result;

	}


	/**
	 * @author wyz-pc 2017年5月12日 下午3:15:37
	 * @param username
	 * @param orgCode
	 * @param apiUserInfoVo
	 * @return msg/code
	 * @Description 企业内部修改用户
	 */
	public String updateOrgUser(String username, String orgCode, ApiUserInfoVo apiUserInfoVo) {


			Map<String, Object> params = new HashMap<String, Object>();
			params.put("token", this.accessToken());
			params.put("username", username);
			params.put("orgCode", orgCode);
			params.put("userInfo", JSON.toJSONString(apiUserInfoVo));
			String jsonData = JSON.toJSONString(params);
			logger.info("updateOrgUser+params->{}", jsonData);
			String result = HttpUtils.sendPostJson(updateOrgUser_url,jsonData);
			logger.info("updateOrgUser+result->{}", result);

     		return result;

	}

	/**
	 * @author wyz-pc 2017年5月12日 下午3:18:29
	 * @param apiUserInfoVo
	 * @return code/msg/result：10存在，20不存在
	 * @Description 通过用户名检查用户是否存在
	 */
	public String checkUserInfo(ApiUserInfoVo apiUserInfoVo) {
		if(!checkCas())
			return null;

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("token", this.accessToken());
		if(StringUtils.isNotEmpty(apiUserInfoVo.getUsername())){
			params.put("username", apiUserInfoVo.getUsername());

		}

		if(StringUtils.isNotEmpty(apiUserInfoVo.getEmail())){
			params.put("email", apiUserInfoVo.getEmail());
		}

		if(StringUtils.isNotEmpty(apiUserInfoVo.getMobile())){
			params.put("mobile", apiUserInfoVo.getMobile());
		}

		String jsonData = JSON.toJSONString(params);
		logger.info("checkUserInfo+params->{}", jsonData);
		String result = HttpUtils.sendPostJson(checkUserInfo_url, jsonData);
		logger.info("checkUserInfo+result->{}", result);
		//String code = JSON.parseObject(result).getString("result");

		return result;
	}

	/**
	 * @author wyz-pc 2017年5月12日 下午3:26:52
	 * @param orgName
	 * @return msg/code/result:orgStatus存在，99不存在
	 * @Description 验证企业信息,先通过用户名查用户id。
	 *              1、如果用户的orgId不为空则通过用户的orgId查询企业，如果查到了返回orgStatus
	 *              2、如果用户的orgId为空则通过传入的orgName查询企业，查到了返回orgStatus，查不到返回99
	 */
	public String checkOrgInfo(String orgName) {
		if(!checkCas())
			return null;

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("token", this.accessToken());
		params.put("orgName", orgName);
		String jsonData = JSON.toJSONString(params);
		logger.info("checkOrgInfo+params->{}", jsonData);
		String result = HttpUtils.sendPostJson(checkOrgInfo_url, jsonData);
		logger.info("checkOrgInfo+result->{}", result);
		//String code = JSON.parseObject(result).getString("result");

		return result;
	}

	public String checkUserData(ApiUserInfoVo apiUserInfoVo) {
		return null;
	}

	/**
	 * @author wyz-pc 2017年5月12日 下午3:35:41
	 * @return
	 * @Description 向主站推送老用户
	 */
	public String pushOldUser(final Integer length) {

		EntityWrapper entityWrapper = new EntityWrapper<>();
		entityWrapper.eq("is_deleted","0").in("id","64346");

		List<MemUser> list = memUserMapper.selectList(entityWrapper);
		if (list == null || list.isEmpty()) {
			return null;
		}

			Integer _len = length;

			if (length == null || length <= 1) {
				_len = 10;
			}
			List<List<MemUser>> temp = ListUtils.splitList(list, _len);
			temp.forEach(users -> {
				ApiUserInfoVo apiUser;
				MemUser user;
				List<ApiUserInfoVo> userInfos = new ArrayList<ApiUserInfoVo>();
				label:
				for (int i = 0, len = users.size(); i < len; i++) {
					apiUser = new ApiUserInfoVo();
					user = users.get(i);
					BeanUtils.copyProperties(user, apiUser);
					apiUser.setSysCode(this.getAppId());
					apiUser.setEncryMode(encryModeBid);
				/*if (StringUtils.isNotBlank(user.getOrgIds())) {
					try {
						apiUser.setOrgId(Integer.valueOf(user.getOrgIds().split(",")[0]));
					} catch (Exception e) {
						continue label;
					}
				}*/
					try {
						if (StringUtils.isNotBlank(user.getOrgIds())) {
							String orgCodes = "";
							String[] orgIdArr = user.getOrgIds().split(",");
							for (String orgId : orgIdArr) {
								MemOrg memOrg = memOrgMapper.selectById(Integer.valueOf(orgId));
								if (memOrg != null && StringUtils.isNotBlank(memOrg.getOrgCode())) {
									orgCodes += memOrg.getOrgCode() + ",";
									apiUser.setOrgCode(memOrg.getOrgCode());
								}
							}
							if (orgCodes.endsWith(",")) {
								orgCodes = orgCodes.substring(0, orgCodes.length() - 1);
							}
							apiUser.setOrgCodes(orgCodes);
						}
					} catch (Exception e) {
						e.printStackTrace();
						continue label;
					}
					userInfos.add(apiUser);
				}
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("token", this.accessToken());
				params.put("userInfos", userInfos);
				String jsonData = JSON.toJSONString(params);
				logger.info("pushOldUser+params->{}", jsonData);
				String result = HttpUtils.sendPostJson(pushOldUser_url, jsonData);
				logger.info("pushOldUser+result->{}", result);
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			});

		return null;
	}

	/**
	 * @author wyz-pc 2017年5月12日 下午3:37:48
	 * @param orgCode
	 * @param username
	 * @param apiUserInfoVos
	 * @return code/msg
	 * @Description 添加企业内部用户
	 */
	public String addOrgUser(String orgCode, String username, List<ApiUserInfoVo> apiUserInfoVos) {
		if(!checkCas())
			return null;

		if (apiUserInfoVos == null || apiUserInfoVos.isEmpty()) {
			return null;
		}
		List<ApiUserInfoVo> userInfos = new ArrayList<ApiUserInfoVo>();
		apiUserInfoVos.forEach(apiUser -> {
			apiUser.setSysCode(this.getAppId());
			apiUser.setOrgCode(orgCode);
			userInfos.add(apiUser);
		});
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("token", this.accessToken());
		params.put("orgCode", orgCode);
		params.put("username", username);
		params.put("userInfos", JSON.toJSONString(userInfos));
		String jsonData = JSON.toJSONString(params);
		logger.info("addOrgUser+params->{}", jsonData);
		String result = HttpUtils.sendPostJson(addOrgUser_url, jsonData);
		logger.info("addOrgUser+result->{}", result);
		return result;
	}

	public String checkOrgData() {
		return null;
	}

	/**
	 * @author wyz-pc 2017年5月12日 下午3:39:52
	 * @return
	 * @Description 向主站推送老企业
	 */
	public String pushOldOrg(Integer length) {
		EntityWrapper entityWrapper = new EntityWrapper();
		entityWrapper.eq("is_deleted","0").in("id","59020");
		List<MemOrg> list = memOrgMapper.selectList(entityWrapper);// 查出所有企业
		if (list == null || list.isEmpty()) {
			return null;
		}
		if (length == null || length <= 1) {
			length = 10;
		}
		List<List<MemOrg>> temp = ListUtils.splitList(list, length);// 将list分段，每段10条
		temp.forEach(orgs -> {// 每10条发送一次
			ApiOrgInfoVo apiOrg;
			MemOrg org;
			List<ApiOrgInfoVo> orgInfos = new ArrayList<ApiOrgInfoVo>();
			for (int i = 0, len = orgs.size(); i < len; i++) {
				apiOrg = new ApiOrgInfoVo();
				org = orgs.get(i);
				BeanUtils.copyProperties(org, apiOrg);
				apiOrg.setAppId(this.getAppId());
				orgInfos.add(apiOrg);
			}
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("token", this.accessToken());
			params.put("orgInfos", orgInfos);
			String jsonData = JSON.toJSONString(params);
			logger.info("pushOldOrg+params->{}", jsonData);
			String result = HttpUtils.sendPostJson(pushOldOrg_url, jsonData);
			logger.info("pushOldOrg+result->{}", result);
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		});
		return null;
	}

	/**
	 * @author wyz-pc 2017年5月18日 下午1:38:34
	 * @param apiOrgInfoVos
	 * @return
	 * @Description 内部 添加企业
	 */
	public String pushAddOrg(List<ApiOrgInfoVo> apiOrgInfoVos) {
		if(!checkCas())
			return null;
		
		List<ApiOrgInfoVo> orgInfos = new ArrayList<ApiOrgInfoVo>();
		apiOrgInfoVos.forEach(apiOrg -> {
			apiOrg.setAppId(this.getAppId());
			orgInfos.add(apiOrg);
		});
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("token", this.accessToken());
		params.put("orgInfos", JSON.toJSONString(orgInfos));
		String jsonData = JSON.toJSONString(params);
		logger.info("pushOldOrg+params->{}", jsonData);
		String result = HttpUtils.sendPostJson(pushOldOrg_url, jsonData);
		logger.info("pushOldOrg+result->{}", result);
		return result;
	}

	private String getAppId() {
		return "zjpt_ebs";
	}
}
